package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.Util.WmThreadLocalUtil;
import com.heima.model.wemedia.dto.KafkaMessageConstants;
import com.heima.model.wemedia.dto.WmNewsDto;
import com.heima.model.wemedia.dto.WmNewsPageReqDto;
import com.heima.model.wemedia.entity.WmMaterial;
import com.heima.model.wemedia.entity.WmNews;
import com.heima.wemedia.dao.WmMaterialDao;
import com.heima.wemedia.dao.WmNewsDao;
import com.heima.wemedia.dao.WmNewsMaterialDao;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自媒体文章表(WmNews)表服务实现类
 *
 * @author makejava
 * @since 2022-04-12 13:54:24
 */
@Service("wmNewsService")
public class WmNewsServiceImpl implements WmNewsService {
    @Resource
    private WmNewsDao wmNewsDao;

    @Resource
    private WmNewsMaterialDao wmNewsMaterialDao;

    @Resource
    private WmMaterialDao wmMaterialDao;


    @Resource
    private KafkaTemplate kafkaTemplate;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public WmNews queryById(Long id) {
        return this.wmNewsDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param wmNews      筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<WmNews> queryByPage(WmNews wmNews, PageRequest pageRequest) {
        long total = this.wmNewsDao.count(wmNews);
        return new PageImpl<>(this.wmNewsDao.queryAllByLimit(wmNews, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews insert(WmNews wmNews) {
        this.wmNewsDao.insert(wmNews);
        return wmNews;
    }

    /**
     * 修改数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews update(WmNews wmNews) {
        this.wmNewsDao.update(wmNews);
        return this.queryById(wmNews.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public ResponseResult deleteById(Long id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmNewsDao.deleteById(id);
        wmNewsMaterialDao.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //文章发布
    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //校验参数
        if (wmNewsDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //封装数据
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //获取到封面图片
        List<String> images = wmNewsDto.getImages();
        //获取内容图片
        List<Map> list = JSON.parseArray(wmNewsDto.getContent(), Map.class);
        //获取到了内容图片
        List<String> contentImages = list.stream().filter(map -> "image".equals(map.get("type")))
                .map(map -> map.get("value").toString()).collect(Collectors.toList());
        //封装type类型
        if (wmNewsDto.getType() == -1) {
            if (contentImages.size() >= 3) {
                images = contentImages.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(3);
            } else if (contentImages.size() > 0 && contentImages.size() < 3) {
                images = contentImages.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(1);
            } else {
                images = Collections.EMPTY_LIST;
                wmNews.setType(0);
            }
        }
        //将封面图片封装到对象中
        wmNews.setImages(StringUtils.join(images.toArray(), ","));
        //文章新增和修改
        saveOrUpdate(wmNews);
        //封面素材文章引用关系
        saveCoverImageRelation(wmNews, images);
        //图片素材文章引用关系
        saveContentImageRelation(wmNews, contentImages);
        //发送消息通知审核服务进行文章审核，状态为1：提交（待审核） 才需要提交
        if (wmNews.getStatus() == 1) {
            kafkaTemplate.send(KafkaMessageConstants.WM_NEWS_AUTO_SCAN_TOPIC, wmNews.getId().toString());
        }
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult list(WmNewsPageReqDto wmNewsPageReqDto) {
        wmNewsPageReqDto.checkParam();
        //校验参数是否为空
        if (wmNewsPageReqDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //封装条件
        Map<String, Object> map = BeanUtil.beanToMap(wmNewsPageReqDto);
        //获取用户id
        Integer id = WmThreadLocalUtil.getUser().getId();
        map.put("userId", id);
        //分页查询
        PageHelper.startPage(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize());
        com.github.pagehelper.Page<WmNews> wmNews = wmNewsDao.selectPage(map);
        ResponseResult result = new PageResponseResult(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), (int) wmNews.getTotal());
        result.setData(wmNews.getResult());
        return result;
    }

    private void saveContentImageRelation(WmNews wmNews, List<String> contentImages) {
        if (wmNews.getStatus() == 0) {
            return;
        }
        //图片素材去重
        List<String> collect = contentImages.stream().distinct().collect(Collectors.toList());
        //获取素材id
        List<WmMaterial> list = wmMaterialDao.queryByImages(collect);
        //获取素材id
        List<Long> materialId = list.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
        //设置类型
        Integer type = 0;
        //添加素材文章关系
        wmNewsMaterialDao.saveImageRelation(materialId, wmNews.getId(), type);
    }

    private void saveCoverImageRelation(WmNews wmNews, List<String> images) {
        if (wmNews.getStatus() == 0) {
            return;
        }
        //封面素材去重
        List<String> collect = images.stream().distinct().collect(Collectors.toList());
        //获取素材id
        List<WmMaterial> list = wmMaterialDao.queryByImages(collect);
        //获取素材id
        List<Long> materialId = list.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
        //设置类型
        Integer type = 1;
        //添加素材文章关系
        wmNewsMaterialDao.saveImageRelation(materialId, wmNews.getId(), type);
    }

    private void saveOrUpdate(WmNews wmNews) {
        //先判断该请求是添加请求还是修改请求、
        wmNews.setUserId(Long.valueOf(WmThreadLocalUtil.getUser().getId()));
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable(1);
        if (wmNews.getId() == null) {
            wmNewsDao.insert(wmNews);
            return;
        }
        //修改文章
        wmNewsDao.update(wmNews);
        //删除文章素材关联信息
        wmNewsMaterialDao.deleteById(wmNews.getId());
    }
}
